#include "timer.h"
#include "usart.h"
#include "magnetic.h"

#include "stm8l15x_tim2.h"

#include <string.h>

int time_total = 0;
int time_seconds = 0;

void Timer2_Initialize(int seconds)
{
    time_seconds = seconds;
    // 时钟配置
    CLK_PeripheralClockConfig(CLK_Peripheral_TIM2, ENABLE);
    // 1分频，向上计数，每1S定时中断一次
    TIM2_DeInit();
    TIM2_TimeBaseInit(TIM2_Prescaler_16, TIM2_CounterMode_Up, 1000);
    TIM2_ARRPreloadConfig(ENABLE);
    TIM2_ITConfig(TIM2_IT_Update, ENABLE);
    TIM2_Cmd(DISABLE);
}

void Timer2_Start(void)
{
    TIM2_Cmd(ENABLE);
}

void Timer2_Stop(void)
{
    TIM2_Cmd(DISABLE);
}

/**
  * @brief TIM2 Update/Overflow/Trigger/Break Interrupt routine.
  * @par Parameters:
  * None
  * @retval
  * None
  */
char message[15] = "turns:";
INTERRUPT_HANDLER(TIM2_UPD_OVF_TRG_BRK_IRQHandler, 19)
{
    time_total++;
    if (time_total == (1000 * time_seconds)) {
        time_total = 0;
        u8 turns = Magnetic_GetTurns();
        Magnetic_ResetTurns();
        itoa(turns, message + 6, 10);
        Usart1_WriteData(message, strlen(message));
    }
    TIM2_ClearITPendingBit(TIM2_IT_Update);
}